<template>
	<view>
		<z-paging ref="paging" v-model="dataList" :refresher-out-rate="0.8" auto-scroll-to-top-when-reload
			safe-area-inset-bottom bg-color="#fff" @query="queryList" :auto-clean-list-when-reload="false"
			:auto-scroll-to-top-when-reload="false"
			empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
			empty-view-text="暂无内容" :refresher-status.sync="refresherStatus">
			<view>
				<view class="pepole">
					<view class="flex_wrap row_between">
						<u--text text="蜂币明细" color="#FFF" size="32rpx" />
						<u--text text="提现申请>" color="#ffffff" align="right" size="36rpx" @click="showQRCodePopup = true" />
					</view>
					<view class="flex_wrap row_between row_middle bottom">
						<view>
							<u--text :text="(detailInfo.haveAlreadySettled || '0.00')" color="#FFF" size="40rpx"
								align="center" />
							<u--text text="已结算(元)" color="#FFF" size="28rpx" align="center" margin="28rpx 0 0" />
						</view>
						<view>
							<u--text :text="(detailInfo.toBeSettled || '0.00')" color="#FFF" size="40rpx"
								align="center" />
							<u--text text="未结算(元)" color="#FFF" size="28rpx" align="center" margin="28rpx 0 0" />
						</view>
						<view>
							<u--text :text="(detailInfo.inWithdrawAmount || '0.00')"
								color="#FFF" size="40rpx" align="center" />
							<u--text text="提现中(元)" color="#FFF" size="28rpx" margin="28rpx 0 0" align="center" />
						</view>
					</view>
				</view>
				<view style="width: 460rpx;">
					<u-tabs :current="currentTab" :list="tabList" @change="tabChange" :scrollable="false" :activeStyle="{
						  color: '#3D3D3D',
						  fontWeight: 'bold',
					  }" :inactiveStyle="{
						  color: '#777',
					  }"></u-tabs>
				</view>
				<view class="tabLine">
					<u-line color="#D8D8D8" />
				</view>
			</view>
			<view class="orderList" v-for="(item, index) in dataList" :key="index">
				<view class="flex_wrap row_between">
					<!-- <view class="line1" style="width: 500rpx;"> {{item.goodsName}}</view> -->
					<view class="line1" style="width: 500rpx;">
						{{item.popularizeFlow == 1 ? '蜂币提现·' + ' '+(item.nickName || '')+(item.orderPayCustomerPhone || '') : '蜂友奖励·' + ' '+(item.nickName || '')+(item.orderPayCustomerPhone || '')}}</view>
					<u-text v-if="item.popularizeFlow == 1" :text="'-'+ (numDiv(item.popularizePrice, 100))" color="#3D3D3D" size="28rpx"
						align="right" />
					<u-text v-else :text="'+'+ (numDiv(item.popularizePrice, 100))" color="#3D3D3D" size="28rpx"
						align="right" />
				</view>
				<view class="flex_wrap row_between orderList_btm">
					<u-text :text="item.createTime" color="#777" size="24rpx" />
					<u-text v-if="item.refundStatus == 0 && item.popularizeFlow == 1" :text="item.settlementStatus ? '已结算' : '提现中' "
						:color="item.settlementStatus ? '#18C195' : '#FF7B00' " size="32rpx" align="right" />
					<u-text v-if="item.refundStatus !== 0" :text="item.refundStatus == 1 ? '退款中' : '已退款' "
						:color="item.refundStatus == 1 ? '#c1282a' : '#ff301d' " size="32rpx" align="right" />
				</view>
				<u-line color="#D8D8D8" />
			</view>

			<u-modal :show="moneyShow" showCancelButton title="提现金额" @confirm="moneyConfirm" @cancel="moneyEdit" :confirmText="bankName ?'确认' : '下一步'">
				<view style="width: 560rpx; margin: 0 auto">
					<u-text text="提现金额:" size="32rpx" margin="20rpx 0" />
					<u--input type="number" placeholder="请输入提现金额" clearable v-model="moneyNum" :customStyle="{
					background: '#F7F7F7',
					borderRadius: '16rpx 16rpx 16rpx 16rpx',
					border: 'none',
					height: '80rpx',
				}" :placeholderStyle="{
					fontSize: '28rpx',
					color: '#aaa',
				}"></u--input>
					<u-text text="提示: 发起申请后，次月25号发放!" color="#999" size="28rpx" margin="32rpx 0 0" />
				</view>
			</u-modal>
			<u-modal :show="moneyShow1" showCancelButton title="提现银行卡" @confirm="moneyConfirm1" @cancel="moneyEdit1" confirmText="下一步">
				<view style="width: 560rpx; margin: 0 auto">
					<u-text text="提现银行：" size="32rpx" margin="20rpx 0" />
					<u--input type="text" placeholder="请输入提现银行" clearable v-model="bankName" :customStyle="{
						background: '#F7F7F7',
						borderRadius: '16rpx 16rpx 16rpx 16rpx',
						border: 'none',
						height: '80rpx',
					}" :placeholderStyle="{
						fontSize: '28rpx',
						color: '#aaa',
					}"></u--input>
					
					<u-text text="银行卡号:" size="32rpx" margin="48rpx 0 20rpx" />
					<u--input type="number" placeholder="请输入提现银行卡号" clearable v-model="bankCardNumber" :customStyle="{
						background: '#F7F7F7',
						borderRadius: '16rpx 16rpx 16rpx 16rpx',
						border: 'none',
						height: '80rpx',
					}" :placeholderStyle="{
						fontSize: '28rpx',
						color: '#aaa',
					}"></u--input>
				</view>
			</u-modal>
			<u-modal :show="moneyShow2" showCancelButton title="上传您的身份证照片" @confirm="moneyConfirm2" @cancel="moneyEdit2" confirmText="确认">
				<view style="width: 560rpx; margin: 0 auto">
					<view>
						<u-text text="身份证人脸面:" size="32rpx" margin="20rpx 0" />
						<u-upload :maxCount="1" :fileList="fileList" @delete="beforeDelete" @afterRead="afterRead"
							width="196rpx" height="196rpx">
							<image src="/static/images/card/idcard2.png" mode="widthFix"
								style="width: 196rpx;height: 196rpx"></image>
						</u-upload>
					</view>
					<view>
						<u-text text="身份证国徽面:" size="32rpx" margin="48rpx 0 20rpx" />
						<u-upload :maxCount="1" :fileList="fileList1" @delete="beforeDelete1" @afterRead="afterRead1"
							width="196rpx" height="196rpx">
							<image src="/static/images/card/idcard1.png" mode="widthFix"
								style="width: 196rpx;height: 196rpx"></image>
						</u-upload>
					</view>
				</view>
			</u-modal>
		</z-paging>
			
			<!-- 二维码弹窗组件 -->
				<qrcode-popup
				  :show="showQRCodePopup"
				  title="请前往小程序提现"
				  @close="handleQRCodeClose"
				  @save-success="handleQRCodeSaveSuccess"
				  @save-fail="handleQRCodeSaveFail"
				/>
		</view>
	</template>

	<script>
		import {
			baseUrl
	} from "@/config/tendIdConfig.js";
	import {
		popularizeInfo,
		settlementAmount
	} from "@/api/userManageSalesman.js";
	import {
		applyWithdraw
	} from "@/api/coupon.js";
	import {
			numDiv,
			numAdd
		} from "@/js_sdk/nl-precisionNum/precisionNum.js";
		import QRCodePopup from '@/components/qrcode-popup/qrcode-popup.vue';
		
		export default {
			components: {
				QRCodePopup,
			},
		data() {
			return {
				moneyShow: false,
				moneyShow1: false,
				moneyShow2: false,
				moneyNum: '',
				bankName:'',//银行
				showQRCodePopup: false,
				appLogoImage: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/23/0e6265fd99fa49a9bacf3791420d6de6.png", // 使用app logo作为临时二维码图片
				bankCardNumber:'',//银行卡号
				fileList:[],//身份证正面
				fileList1:[],//身份证反面
				toBeSettled:'',
				numAdd,
				numDiv,
				tabList: [{
						name: "全部",
						id: 0,
					},
					{
						name: "已结算",
						id: 1,
					},
					{
						name: "未结算",
						id: 2,
					},
				],
				currentTab: 0,
				dataList: [],
				detailInfo: {}
			};
		},
		onLoad(op) {
			this.bankCardNumber = op.bankCardNumber || ''
			this.bankName = op.bankName || ''
			console.log(op,'>>>>',this.bankName)
			this.fileList =op.idCardFront ? [{ url: op.idCardFront}] : [];
			this.fileList1 =op.idCardBack ? [{ url: op.idCardBack}] : [];
		},
		methods: {
			beforeDelete(event) {
				//删除的附件从fileList中删掉
			    this.fileList.splice(event.index, 1);
			},
			beforeDelete1(event) {
				//删除的附件从fileList中删掉
			    this.fileList1.splice(event.index, 1);
			},
			async afterRead(event) {
			    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			    let lists = [].concat(event.file);
			    let fileListLen = this.fileList.length;
			    lists.map((item) => {
			        this.fileList.push({
			            ...item,
			            status: "uploading",
			            message: "上传中",
			        });
			    });
			    for (let i = 0; i < lists.length; i++) {
			        const result = await this.uploadFilePromise(lists[i].url);
			        let item = this.fileList[fileListLen];
			        this.fileList.splice(
			            fileListLen,
			            1,
			            Object.assign(item, {
			                status: "success",
			                message: "",
			                uploadResult: result,
			                url: result,
			            })
			        );
			        fileListLen++;
			    }
			},
			async afterRead1(event) {
			    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			    let lists = [].concat(event.file);
			    let fileListLen = this.fileList1.length;
			    lists.map((item) => {
			        this.fileList1.push({
			            ...item,
			            status: "uploading",
			            message: "上传中",
			        });
			    });
			    for (let i = 0; i < lists.length; i++) {
			        const result = await this.uploadFilePromise(lists[i].url);
			        let item = this.fileList1[fileListLen];
			        this.fileList1.splice(
			            fileListLen,
			            1,
			            Object.assign(item, {
			                status: "success",
			                message: "",
			                uploadResult: result,
			                url: result,
			            })
			        );
			        fileListLen++;
			    }
			},
			async uploadFilePromise(url) {
				 const token = uni.getStorageSync("access_token");
			    const that = this;
			    return new Promise((resolve, reject) => {
			        let a = uni.uploadFile({
			            url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
			            filePath: url,
			            header: {
			              "Content-Type": "multipart/form-data",
			              Authorization: `Bearer ${token}` || "",
			            },
			            name: "file",
			            success: (res) => {
			                const result = JSON.parse(res.data);
			                if (result.code === 200) {
			                    uni.showToast({
			                        title: "上传成功",
			                        icon: "success",
			                    });
			                    setTimeout(() => {
			                        resolve(result.data);
			                    }, 1000);
			                } else {
			                    uni.showToast({
			                        title: "上传失败",
			                        icon: "fail",
			                    });
			                    setTimeout(() => {
			                        reject(result.msg);
			                    }, 1000);
			                }
			            },
			        });
			    });
			},
			
			// 线上活动
			moneyEdit() {
				this.moneyNum = "";
				this.moneyShow = false;
			},
			async moneyConfirm() {
				if (isNaN(this.moneyNum) || this.moneyNum <= 0 || Number(this.moneyNum) > Number(this.toBeSettled))
					return uni.showToast({
						title: "请输入正确金额",
						icon: "none",
					});
				if(this.bankName){
					const params = {
						amount: this.moneyNum,
						bankCardNumber: this.bankCardNumber,
						bankName: this.bankName,
						idCardFront: this.fileList.map((v) => v.url)[0],//人像面
						idCardBack : this.fileList1.map((v) => v.url)[0],//国徽面
					};
					console.log(params,'params>')
					let res = await applyWithdraw(params);
					if (res.code === 200) {
						uni.$u.toast('提现申请创建成功');
						this.moneyEdit();
					}
				}else{
					this.moneyShow = false;
					this.moneyShow1 = true;
				}
				
			},
			moneyEdit1() {
				this.bankName = '';
				this.moneyShow1 = false;
			},
			async moneyConfirm1() {
				if (!this.bankCardNumber.length || !this.bankName.length)
					return uni.showToast({
						title: "请输入到账信息",
						icon: "none",
					});
				this.moneyShow1 = false;
				this.moneyShow2 = true;
			},
			moneyEdit2() {
				this.bankName = ''
				this.moneyShow2 = false;
			},
			async moneyConfirm2() {
				if (
					!this.fileList.length ||
					!this.fileList1.length 
				)
					return uni.$u.toast("请上传图片！");
				const params = {
					amount: this.moneyNum,
					bankCardNumber: this.bankCardNumber,
					bankName: this.bankName,
					idCardFront: this.fileList.map((v) => v.url)[0],//人像面
					idCardBack : this.fileList1.map((v) => v.url)[0],//国徽面
				};
				console.log(params,'params>')
				let res = await applyWithdraw(params);
				if (res.code === 200) {
					uni.$u.toast('提现申请创建成功');
					this.moneyEdit2();
				}
			},
			// async moneyConfirm() {
			// 	if (isNaN(this.moneyNum) || this.moneyNum <= 0 || this.moneyNum > this.toBeSettled)
			// 		return uni.showToast({
			// 			title: "请输入正确金额",
			// 			icon: "none",
			// 		});
			// 	if (!this.bankCardNumber.length)
			// 		return uni.showToast({
			// 			title: "请输入到账银行卡号",
			// 			icon: "none",
			// 		});
			// 	if (
			// 	    !this.fileList.length ||
			// 	    !this.fileList1.length 
			// 	)
			// 		return uni.$u.toast("请上传图片！");
			// 	const params = {
			// 		amount: this.moneyNum,
			// 		bankCardNumber: this.bankCardNumber,
			// 		bankName: this.bankName,
			// 		idCardFront: this.fileList.map((v) => v.url)[0],//人像面
			// 		idCardBack : this.fileList1.map((v) => v.url)[0],//国徽面
			// 	};
			// 	console.log(params,'params>')
			// 	let res = await applyWithdraw(params);
			// 	if (res.code === 200) {
			// 		uni.$u.toast('提现申请创建成功');
			// 		this.moneyEdit();
			// 	}
			// },
			getCommissionDetail() {
				settlementAmount().then((res) => {
					console.log(res, 'res>>')
					if (res.code === 200 && res.data) {
						this.detailInfo = res.data
						this.toBeSettled = this.detailInfo.toBeSettled || '0'
						
					}
				});
			},
			async tabChange(e) {
				this.currentTab = e.index;
				await this.$refs.paging.reload();
			},
			async queryList(pageNo, pageSize) {
				this.getCommissionDetail()
				const that = this;
				let params = {
					pageNum: pageNo,
					pageSize: pageSize,
					settlementStatus: this.currentTab == 0 ? '' : (this.currentTab == 1 ? '1' : '0'),
				};
				let result;
				switch (this.currentTab) {
					case 0:
						result = await popularizeInfo(params);
						break;
					case 1:
						result = await popularizeInfo(params);
						break;
					case 2:
						result = await popularizeInfo(params);
				}
				that.$refs.paging.completeByTotal(result.data.rows, result.total);
			},
			
			// 二维码弹窗相关方法
			handleQRCodeClose() {
				this.showQRCodePopup = false;
			},
			
			handleQRCodeSaveSuccess() {
				console.log('二维码保存成功');
			},
			
			handleQRCodeSaveFail(error) {
				console.log('二维码保存失败:', error);
			},
		},
	};
</script>
<style lang="scss" scoped>
	.pepole {
		padding: 28rpx 38rpx 0;
		width: 694rpx;
		height: 280rpx;
		box-sizing: border-box;
		background: linear-gradient(270deg, #4467d2 0%, #6e8de7 100%);
		background-image: url("https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/05/16/91e17758b1e54602bfe52e0cb393972f.png");
		border-radius: 24rpx;
		background-size: cover;
		margin: 28rpx;
	}

	.bottom {
		margin-top: 60rpx;
	}

	.tabLine {
		padding: 28rpx 28rpx 32rpx;
	}

	.orderList {
		padding: 0 28rpx 32rpx;

		&_btm {
			margin: 20rpx 0 32rpx;
		}
	}
</style>